package com.shioirikukuri.controller;

import com.shioirikukuri.entity.User;
import com.shioirikukuri.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/users")
public class FrontController {

	@Autowired
	private IUserService userService;


	/**
	 * 获取所有前台身份的用户
	 */
	@GetMapping("/front_desk")
	public ResponseEntity<List<User>> getAllFrontDeskUsers() {
		List<User> users = userService.getUsersByRole(User.FRONT_DESK);
		return ResponseEntity.ok(users);
	}


	/**
	 * 验证用户角色是否符合预期
	 *
	 * @param id     用户ID
	 * @param role   预期角色
	 * @return 如果验证成功，返回用户实体；否则返回错误响应
	 */
	private ResponseEntity<User> validateUserRole(Long id, String role) {
		Optional<User> optionalUser = userService.getUserById(id);
		if (optionalUser.isPresent()) {
			User user = optionalUser.get();
			if (role.equals(user.getRole())) {
				return ResponseEntity.ok(user);
			} else {
				return ResponseEntity.badRequest().build(); // 角色不匹配
			}
		} else {
			return ResponseEntity.notFound().build(); // 用户不存在
		}
	}

	/**
	 * 根据ID获取前台身份的用户
	 */
	@GetMapping("/front_desk/{id}")
	public ResponseEntity<User> getFrontDeskUserById(@PathVariable Long id) {
		return validateUserRole(id, User.FRONT_DESK);
	}

	/**
	 * 创建一个前台身份的用户
	 */
	@PostMapping("/front_desk/create")
	public ResponseEntity<User> createFrontDeskUser(@RequestBody User user) {
		user.setRole(User.FRONT_DESK);
		User createdUser = userService.addUser(user);
		return ResponseEntity.status(201).body(createdUser);
	}

	/**
	 * 更新前台身份的用户信息
	 */
	@PutMapping("/front_desk/{id}")
	public ResponseEntity<User> updateFrontDeskUser(@PathVariable Long id, @RequestBody User userDetails) {
		ResponseEntity<User> response = validateUserRole(id, User.FRONT_DESK);
		if (response.getStatusCode().is2xxSuccessful()) {
			userDetails.setRole(User.FRONT_DESK);
			User updatedUser = userService.updateUser(userDetails);
			return ResponseEntity.ok(updatedUser);
		} else {
			return response; // 返回验证失败的结果
		}
	}

	/**
	 * 删除前台身份的用户
	 */
	@DeleteMapping("/front_desk/{id}")
	public ResponseEntity<User> deleteFrontDeskUser(@PathVariable Long id) {
		ResponseEntity<User> response = validateUserRole(id, User.FRONT_DESK);
		if (response.getStatusCode().is2xxSuccessful()) {
			userService.deleteUser(id);
			return ResponseEntity.noContent().build();
		} else {
			return response; // 返回验证失败的结果
		}
	}
}